/**
 * http 请求封装
 * @author tangsj
 * @param {*} url  请求地址
 * @param {*} options 请求参数
 */
import config from '../config';
import utils from '../utils';
import { 
  removeUserToken,
  getUserRefreshToken,
	getUserToken
} from "@/utils/auth";

// 记录请求中的请求数，控制loading显示
let requestCount = 0;
let hasError = false;

export function fetch(url, options) {
  const header = {
    Authorization:`Bearer ${getUserToken()}`,
    refreshToken:getUserRefreshToken()
  };
  // if(options.data.isCanshu){
  //   options.data.caseid = getCaseid()
  //   options.data.usr_toke = getUsrToke()
  // }
  options = Object.assign({
    loading: true,
    method: 'GET',
    data: {},
    holdTip: false,
  }, options);

  return new Promise((resolve, reject) => {
    if (requestCount === 0 && options.loading) {
      hasError = false;
      uni.showLoading({
        title: '加载中...',
      });
    }

    requestCount += 1;
    uni.request({
      url: `${config.apiRoot}${url}`,
      data: options.data,
      method: options.method,
      header,
      success: (res) => {
        if (res.data.code == 401) {
          removeUserToken()
          uni.showModal({
            title: '温馨提示',
            content: '登录失效，请重新登录',
            confirmText: '重新登录',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
                uni.reLaunch({
                  url: '/pages/index/index'
                });
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
          return resolve();
          // uni.redirectTo({
					// 	url: '/pages/index/index',
					// })
          // wx.showToast({
          //     title: "登录信息已失效~",
          //     icon: "none",
          //     duration:2000,
          // });
          return
          // uni.showToast({
          //   title: '登录失效请重新登录',
          //   icon: 'none',
          // });
          // uni.redirectTo({
          //   url:`/pages/index/index`
          // })
          // if (!options.holdTip) {
          //   hasError = true;
          //   if(!hasError){
          //     hasError = true;
              
          //   }
          // }
        }
        return resolve(res.data || {});
      },
      fail: () => {
        hasError = true;

        uni.showToast({
          title: '服务器异常！',
          icon: 'none',
        });

        reject({
          msg: '服务器异常！',
        });
      },
      complete: () => {
        requestCount -= 1;
        if (requestCount === 0 && options.loading) {
          if (hasError) {
            setTimeout(() => {
              uni.hideLoading();
            }, 2000);
          } else {
            uni.hideLoading();
          }
        }
      },
    });
  });
}

const http = {
  get(url, data = {}, options = {}) {
    return fetch(url, {
      method: 'GET',
      data: data.params,
      ...options,
    });
  },
  post(url, data = {}, options = {}) {
    if (data.params) {
      // 将param放到url 参数里面
      const query = utils.buildQueryString(data.params);
      url += `?${query}`;
      delete data.params;
    }
    return fetch(url, {
      method: 'POST',
      data,
      ...options,
    });
  },
};

export default http;
